import urllib.request
import urllib.parse


def create_request(page):
    base_url = 'https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&'
    data = {
        'start': (page - 1) * 20,
        'limit': 20
    }
    data = urllib.parse.urlencode(data)
    url = base_url + data
    print(url)
    headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }
    return urllib.request.Request(url=url, headers=headers)


def get_content(request):
    response = urllib.request.urlopen(request)
    return response.read().decode('utf-8')


if __name__ == '__main__':
    start = input('请输入起始页码')
    end = input('请输入结束页码')
    for i in range(int(start), int(end) + 1):
        request = create_request(i)
        content = get_content(request)
        with open('douban' + str(i) + '.json', 'w', encoding='utf-8') as fp:
            fp.write(content)
